const express = require("express");
const UserModel = require("../models/user");
const router = express.Router();

// 用户创建页面
router.get("/register", (req, res) => {
  res.render("user/register");
});

// 用户登录页面
router.get("/login", (req, res) => {
  res.render("user/login");
});

// 用户注册动作
router.post("/register", async (req, res) => {
  const user = new UserModel(req.body);

  await user.save();

  res.redirect("/users/login");
});

// 用户登录动作
router.post("/login", async (req, res) => {
  // 1. 取出username与password参数
  let username = req.body.username;
  let password = req.body.password;

  // 2. 根据username查找用户
  const user = await UserModel.findOne({ username });
  let isOK = false;

  if (user) {
    isOK = await user.comparePassword(password);
  }

  if (!isOK) {
    throw new Error("用户名或密码错误");
  } else {
    req.session.user = {
      _id: user._id,
      username: user.username
    };
    res.redirect("/");
  }
});

module.exports = router;
